package com.jt.provider.controller;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义BlockException的异常处理对象
 */
@Component
public class DefaultSentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       BlockException e) throws Exception {
        //设置响应内容类型,以及告诉高客户端应该按什么编码显示数据
        response.setContentType("text/html;charset=utf-8");
        //设置响应状态码(将来可以基于这个状态码进行相关处理)
        response.setStatus(429);
        //获取响应输出流对象
        PrintWriter out = response.getWriter();
        String msg="访问太频繁,稍等片刻再访问.";
        if (e instanceof DegradeException){
            msg="服务不可用,请稍候";
        }else if (e instanceof AuthorityException){
            msg="你不配访问";
        }
        out.print(msg);
        out.flush();
        out.close();
    }
}